package com.xjm.api.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xjm.entity.model.OrderItemsModel;
import com.xjm.entity.model.OrdersModel;
import com.xjm.entity.vo.Result;
import com.xjm.service.IOrderItemsService;
import com.xjm.service.IOrdersService;
import com.xjm.utils.UserContext;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xjm
 * @since 2025-03-03
 */
@RestController
@RequestMapping("/user/order")
@RequiredArgsConstructor
public class WebOrdersController {

    private final IOrdersService ordersService;
    private final IOrderItemsService orderItemsService;

    @GetMapping("/list")
    public Result<List<OrdersModel>> getOrderById(@RequestParam(required = false) String status) {
        Integer userId = UserContext.getUserId();
        LambdaQueryWrapper<OrdersModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrdersModel::getUserId, userId);
        queryWrapper.eq(StringUtils.isNotBlank(status) && !"all".equals(status), OrdersModel::getStatus, status);
        List<OrdersModel> list = ordersService.list(queryWrapper);
        list.forEach(o -> o.setOrderItems(orderItemsService
                .list(new LambdaQueryWrapper<OrderItemsModel>().eq(OrderItemsModel::getOrderId, o.getId()))));
        return Result.success(list);
    }

    /**
     * 创建订单和订单项
     * @param data 订单和订单项
     */
    @PostMapping
    public Result<Void> add(@RequestBody OrdersModel data) {
        ordersService.createOrderWithItems(data);
        return Result.success();
    }


    @PutMapping("/{id}/cancel")
    public Result<Void> cancelOrder(@PathVariable String id) {
        ordersService.cancel(id);
        return Result.success();
    }

    @PutMapping("/{id}/pay")
    public Result<Void> payOrder(@PathVariable String id) {
        ordersService.pay(id);
        return Result.success();
    }
}
